#include <allegro.h>
#include <stdio.h>
#include "stage.h"
#include "player.h"
#include "object.h"

#define SCR_W 800
#define SCR_H 600
#define DELAY_MSEC 40
#define MIO_X_SPEED 5

volatile int counter = 0;
void counter_ticker() {
	counter++;
}
END_OF_FUNCTION(counter_ticker);

volatile int seconds = 0;
void seconds_ticker() {
	seconds++;
}
END_OF_FUNCTION(seconds_ticker);

int main() {
	LOCK_VARIABLE(counter);
	LOCK_FUNCTION(counter_ticker);

	allegro_init();

	install_timer();
	install_keyboard();
	install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL);

	set_color_depth(24);
	set_gfx_mode(GFX_AUTODETECT_WINDOWED, SCR_W, SCR_H, 0, 0);

	BITMAP* buffer = create_bitmap(SCR_W, SCR_H);
	
	stage stage1("stage1.txt");

	char str[] = "player.bmp"; /* FIXME: gambiarra */
	player mio(SCR_W, SCR_H, MIO_X_SPEED, str);

	install_int(seconds_ticker, 1000);

	install_int(counter_ticker, 1);
	int delay = 0;

	while (!key[KEY_ESC]) {
		delay += counter;
		counter = 0;

		printf("%d\n", delay);	
		if (delay > DELAY_MSEC) {
			clear_keybuf();

			acquire_screen();

			clear_to_color(buffer, makecol(255, 255, 255));

			mio.draw(buffer);
			mio.move(SCR_W);

			for (unsigned int i = 0; i < stage1.notes.size(); i++) {
				if (stage1.notes[i].exists(seconds)) {
					if (mio.can_catch(stage1.notes[i])) {
						stage1.notes.erase(stage1.notes.begin() + i);
					}
					if (stage1.notes[i].is_out(SCR_W)) {
						stage1.notes.erase(stage1.notes.begin() + i);
					}
					else {
						stage1.notes[i].draw(buffer);
						stage1.notes[i].move();
					}
				}
			}

			if (stage1.notes.size() == 0) {
				return 0;
			}

			draw_sprite(screen, buffer, 0, 0);

			release_screen();

			delay = 0;
		}
	}
	return 0;
}
END_OF_MAIN();
